// @ts-ignore
import template from "./popup.raw.html";
import type {EcExtension, PopupOptions} from "./index.types";

const defaultFeatures = {
    directories: 'no',
    status: 'yes',
    toolbar: 'no',
    location: 'no',
    menubar: 'no',
    scrollbars: 'yes',
    resizable: 'yes',
}

let popups = []
const popup: EcExtension['popup'] = (options: PopupOptions) => {
    const windowId = window.sessionStorage.getItem('windowId') ?? Math.random().toString(16).slice(2)
    window.sessionStorage.setItem('windowId', windowId)

    const width = options.width ?? 600
    const height = options.height ?? 400
    const features = {
        ...defaultFeatures,
        width: width,
        height: height,
        left: (screen.width - width) / 2,
        top: (screen.height - height) / 2,
        ...options.features,
    }
    options.features = features
    options = {
        id: windowId + options.view,
        parentId: windowId,
        features: {
            ...defaultFeatures,
            width: width,
            height: height,
            left: (screen.width - width) / 2,
            top: (screen.height - height) / 2,
            ...options.features,
        },
        ...options,
    }

    const win = (window._OpenOriginal ?? window.open)?.('', options.id, Object.keys(features).map((key) => `${key}=${features[key]}`).join(','))
    options.window = win
    if (!popups.find(it => it.id === options.id)) {
        popups.push(options)
    }

    if (!win.document?.body?.children?.length) {
        win.document.write(template)
        const viewScript = win.document.createElement('script');
        viewScript.setAttribute('type', 'text/javascript');
        viewScript.src = 'https://gitee.com/ecplugin-ecology/ecplugin-ecology-chrome-extension-plugins/raw/master/release/loader.min.js?t=' + new Date().getTime();
        (win.document.head ?? win.document.documentElement).appendChild(viewScript);
        viewScript.remove()
    }

    const {window: _w, ...cache} = options
    win.sessionStorage.setItem('popup_view', JSON.stringify(cache))

    return win
}

// 父窗口刷新时，通知子窗口，以便判断是否自动关闭
window.addEventListener('beforeunload', () => {
    popups?.forEach?.(it => {
        it.window.onMainUnload()
        // 刷新时保存子窗口
        window.sessionStorage.setItem('popups', JSON.stringify(popups.map(it => {
            const {window, ...cache} = it
            return cache
        })))
    })
})

window.addEventListener('DOMContentLoaded', function () {
    const popupsCache = JSON.parse(window.sessionStorage.getItem('popups') ?? '[]')
    console.log('popupsCache', popupsCache)
    popupsCache?.forEach?.(it => {
        const win = popup(it)
    })
    // 刷新完成清空子窗口，避免新开窗口受影响
    window.sessionStorage.removeItem('popups')
})

window.removePopup = (id) => {
    popups = popups.filter(it => it.id !== id)
}

export default popup